#include "GraphicsItems.h"

#include "LeGraphicsView/LeGraphicsItemLayer.h"
#include "LeGraphicsView/LeGraphicsScene.h"

#include <QDebug>
#include <QStyleOptionGraphicsItem>

TerminalItem::TerminalItem(const Terminal *terminal)
    : LeGraphicsItem(LeGraphicsFeature::GftPin)
    , m_terminal(terminal)
    , m_label(new LeGraphicsLabelItem(LeGraphicsFeature::GftText, this))
{
    QFont font;
    font.setPixelSize(20);
    m_label->setFont(font);
}

TerminalItem::~TerminalItem()
{

}

void TerminalItem::setLabel(const QString &text)
{
    m_label->setText(text);
}

QString TerminalItem::label() const
{
    return m_label->text();
}

const Terminal *TerminalItem::terminal() const
{
    return m_terminal;
}

void TerminalItem::synchronise()
{
    prepareGeometryChange();
}

QRectF TerminalItem::boundingRect() const
{
    return m_terminal->boundingBox();
}

void TerminalItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(widget)

    GraphicsStyleOption itemOption;
    itemOption.exposedRect = option->exposedRect;
    itemOption.palette = layer()->graphicsPalette(featureType());
    itemOption.state = state();
    LeGraphicsStyle *style = graphicsScene()->graphicsStyle();
    style->drawRect(&itemOption, painter, m_terminal->boundingBox());
    //style->drawCircle(&itemOption, painter, QPointF(), m_terminal->boundingBox().width()/2.0);
}

LeGraphicsItem *TerminalItem::clone() const
{
    return nullptr;
}

QRectF Terminal::boundingBox() const
{
    QPointF topLeft;
    switch (m_anchor)
    {
        case L7::AnchorTopLeft:
            topLeft.rx() = 0;
            topLeft.ry() = 0;
            break;
        case L7::AnchorTopCenter:
            topLeft.rx() = -m_size.width()/2.0;
            topLeft.ry() = 0;
            break;
        case L7::AnchorTopRight:
            topLeft.rx() = -m_size.width();
            topLeft.ry() = 0;
            break;
        case L7::AnchorRightCenter:
            topLeft.rx() = -m_size.width();
            topLeft.ry() = -m_size.height()/2.0;
            break;
        case L7::AnchorBottomRight:
            topLeft.rx() = -m_size.width();
            topLeft.ry() = -m_size.height();
            break;
        case L7::AnchorBottomCenter:
            topLeft.rx() = -m_size.width()/2.0;
            topLeft.ry() = -m_size.height();
            break;
        case L7::AnchorBottomLeft:
            topLeft.rx() = 0;
            topLeft.ry() = -m_size.height();
            break;
        case L7::AnchorLeftCenter:
            topLeft.rx() = 0;
            topLeft.ry() = -m_size.height()/2.0;
            break;
        case L7::AnchorCenter:
            topLeft.rx() = -m_size.width()/2.0;
            topLeft.ry() = -m_size.height()/2.0;
            break;
    }
    return QRectF(topLeft, m_size);
}
